// pages/iotEquipmentDetail/iotEquipmentDetail.js
const app = getApp();
//定时器
var timer=null;
const util = require('../../utils/util');
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import CommonService from '../../utils/service/commonService.js';
//去掉尾部的0
const regexp=/(?:\.0*|(\.\d+?)0+)$/;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //地区中心点-纬度
    latitude: '',
    //地区中心点-经度
    longitude: '',
    //地图上标记
    markers:[],
    //位置状态
    address:'暂无位置信息',
    //传参来的gps编码
    imei:null,
    //设备信息
    info:{},
    //物联网信息
    iotdata:{},
    //登录的客户信息
    userInfo:{},
    //客户设备型号
    memberTypeStr:'',
    //厂家设备型号
    factoryTypeName:'',
    //图片
    iconUrlStr:'',
    //用户权限
    authority:null,
    //显示信息区域-避免数据延迟
    showInfo:false,
    //平台id
    myAppId:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('物联网信息传参');
    console.log(options);

    this.setData({
      imei: options.imei,
      userInfo: app.globalData.userInfo,
      authority: app.globalData.authority,
      myAppId: app.globalData.myAppId
    })

    //如果有图片先赋值，这样地图上会第一时间显示图片
    if(options.iconUrl){
      this.setData({
        iconUrlStr: options.iconUrl
      })
    }

    //获取设备信息
    this.getEquipmentInfo();

    //获取物联网设备数据
    this.getIotInfo();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //每隔一段时间重新请求数据
    timer=setInterval(() => {
      this.getIotInfo();
    }, 1000*30);
  },

  //获取设备信息
  getEquipmentInfo(){
    let param={
      isAuth:false,
      className:'equipment',
      data:{
        imei:this.data.imei,
        selectFields:['equipmentNo','equipmentBase','memberType','project','memberTypeName','iconUrl','equipmentBaseName','businessType','workAmount','workUnit']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result){
        let result=res.data.data.result;
        console.log('设备信息');
        console.log(result[0]);

        //处理客户型号
        if(result[0].memberTypeName){
          this.setData({
            memberTypeStr: result[0].memberTypeName
          })
        }else if(result[0].memberType.length && result[0].memberType[0].name){
          this.setData({
            memberTypeStr: result[0].memberType[0].name
          })
        }

        //处理厂家型号
        if(result[0].equipmentBaseName){
          this.setData({
            factoryTypeName: result[0].equipmentBaseName
          })
        }else if(result[0].equipmentBase.length && result[0].equipmentBase[0].typeCode){
          this.setData({
            factoryTypeName: result[0].equipmentBase[0].typeCode
          })
        }

        //处理图片
        if(result[0].iconUrl){
          this.setData({
            iconUrlStr: result[0].iconUrl
          })
        }else if(result[0].memberType.length && result[0].memberType[0].iconUrl){
          this.setData({
            iconUrlStr: result[0].memberType[0].iconUrl
          })
        }

        this.setData({
          info: result[0]
        })
      }
    }).catch((error) => {
    })
  },

  //获取物联网设备数据
  getIotInfo(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let parameter={
      imei:this.data.imei
    }

    CommonService.goFindOneByImei(parameter).then(res=>{
      Toast.clear();
      let result=res.data.data.result;
      if(result && (JSON.stringify(result)!="{}")){
        let vol=result.vol,
            maxvol=result.maxvol,
            minvol=result.minvol;

        if(vol==null || vol<=0){          
          result.remainingElectricity=0;
        }else if(vol!=null && vol-minvol==0){
          result.remainingElectricity=0;
        }else if(maxvol-minvol==0){
          result.remainingElectricity=100;
        }else if(vol==maxvol && vol==minvol && maxvol==minvol){
          result.remainingElectricity=100;
        }else{
          let str=(((vol-minvol)/(maxvol-minvol)*100).toFixed(2)).replace(regexp,'$1'); 
          if(str && !isNaN(str)){
            let remainingElectricity=Number(new String(str));
            if(remainingElectricity<0){
              result.remainingElectricity=0;
            }else if(remainingElectricity>100){
              result.remainingElectricity=100;
            }else{
              result.remainingElectricity=remainingElectricity;
            }
          }
        }

        //处理在线离线-当前时间大于数据日期16分钟是离线
        if(result.ctm){
          let ctm=result.ctm;
          if(ctm.indexOf('T')==-1){
            //日期格式替换兼容ios
            ctm=new Date(ctm.replaceAll('-','/'));
          }else{
            ctm=new Date(ctm);
          }

          let currentTime=new Date();
          let num=currentTime-ctm;
          if(num>16*60*1000){
            result.onLineJudge=false;
          }else{
            result.onLineJudge=true;
          }
        }else{
          result.onLineJudge=false;
        }

        console.log('~~~物联网数据~~~');
        console.log(result);

        //设置页面数据
        this.setData({
          iotdata: result,
          showInfo:true
        });

        if(result.lat && result.lng){
          this.setData({
            latitude: result.lat,
            longitude: result.lng,
          });
          //显示标注
          this.showMarkers();
          //地理位置解析
          this.locationAnalysis();
        }else{
          Toast.fail('正在获取位置信息...');
          this.setData({
            latitude: '39.898331',
            longitude: '116.411168'
          });
        }
      }else{
        Toast.fail('正在获取位置信息...');
        this.setData({
          showInfo:true,
          latitude: '39.898331',
          longitude: '116.411168'
        });
      }
    }).catch((error) => {
      Toast.fail('正在获取位置信息...');
      this.setData({
        showInfo:true,
        latitude: '39.898331',
        longitude: '116.411168'
      });
    })
  },

  //显示标注
  showMarkers(){
    let user=app.globalData.userInfo;
    //物联网信息
    let info=this.data.iotdata;
    //设备信息
    let eInfo=this.data.info;
    //图标
    let iconUrl=null;

    if(user.type!=2){
      iconUrl=this.data.iconUrlStr
    }

    if(user.type==2 && eInfo.equipmentBase && eInfo.equipmentBase.length){
        iconUrl=eInfo.equipmentBase[0].iconUrl
    }

    let markers=[];
    let marker={
      id:0,
      latitude: info.lat,
      longitude: info.lng,
      width: 50,
      height: 50
    }
    if(iconUrl){
      marker.iconPath=iconUrl;
    }
    markers.push(marker);
    this.setData({
			markers: markers
		});
  },

  //逆地址解析
  locationAnalysis(){
    let place = this.data.iotdata;
    let _this = this;
    let location = place.lat +','+ place.lng;
    let key = app.globalData.tencentKey;

    wx.request({
		  url: 'https://apis.map.qq.com/ws/geocoder/v1/?location='+location+'&key='+key+'&get_poi=1',
		  method: "GET",
		  success(res) {
        if(res.statusCode==200 && res.data){
          _this.setData({
            address: res.data.result.address
          })  
        }
		  }
    })
  },

  //点击标注
  markertap(e) {
    this.getIotInfo();
  },

  //查轨迹
  trajectory(){ 
    let obj={
      imei: this.data.imei,
      iotData: this.data.iotdata
    }
    wx.navigateTo({
      url: '/pages/trajectory/trajectory?paramObj=' + JSON.stringify(obj)
    })
  },

  //工作时段
  operationalCount:function(){
    let obj={
      imei: this.data.imei,
      workAmount: this.data.info.workAmount,
      workUnit: this.data.info.workUnit
    }
    wx.navigateTo({
      url: '/pages/operationStatistics/operationStatistics?paramObj=' + JSON.stringify(obj)
    })
  },

  //指令
  direct: function (e) {
    //设备信息
    let info=this.data.info;
    //物联网信息
    let iotInfo=this.data.iotdata;
    //如果物联网信息无imei就取设备的imei
    if(!iotInfo.imei){
      iotInfo.imei=this.data.imei;
    }
    //设备equipmentType值传过去
    iotInfo.equipmentType=info.equipmentType;

    wx.navigateTo({
      url: '/pages/direct/direct?obj=' + JSON.stringify(iotInfo)
    })
  },

  //设置围栏
  enclosure: function(e) {
    var _this = this;
    wx.navigateTo({
      url: '/pages/enclosure/enclosure?obj=' + util.changeJsonUrl(JSON.stringify(_this.data.info), 1)
    })
  },

  //离线提示信息
  onShowOffTips(){
    Toast({
      message: '设备离线，可以将设备移动到地上等信号好的地方，等待10分钟系统自动补传数据，只能补传数据日期在2天内的数据。',
      duration:5000
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    //清除定时器
    clearInterval(timer);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //清除定时器
    clearInterval(timer);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})
